package com.fox.runner;

import com.fox.config.constant.SystemConstants;
import com.fox.domain.entity.Article;
import com.fox.mapper.ArticleMapper;
import com.fox.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息  id  viewCount
        List<Article> articles = articleMapper.selectList(null);
        //viewCountMap 的 value 为 Integer是因为: 如果在redis中存储long类型可能会出错
        //比如 存储long类型的值 1，在redis里面存储会变成 1l，所以会报错。
        Map<String, Integer> viewCountMap = new HashMap<>();
        for (Article article : articles) {
            viewCountMap.put(article.getId().toString(),article.getViewCount().intValue());
        }
        //存储到redis中
        redisCache.setCacheMap(SystemConstants.ARTICLE_VIEW_COUNT_KEY,viewCountMap);
    }
}
